package com.to8to.autotask.newlundan;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.sql.rowset.CachedRowSet;

import org.apache.thrift.TException;
import org.elasticsearch.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Splitter;
import com.to8to.autotask.newlundan.entity.Company;
import com.to8to.autotask.newlundan.entity.GDInfo;
import com.to8to.autotask.newlundan.entity.GeoPoint;
import com.to8to.autotask.newlundan.entity.LundanConfig;
import com.to8to.autotask.newlundan.entity.ZXBOrder;
import com.to8to.autotask.rpc.CallClient;
import com.to8to.autotask.util.DBUtil;
import com.to8to.autotask.util.Utils;
import com.to8to.commons.utils.StringUtil;
import com.to8to.es.util.LogUtil;
import com.to8to.thrift.diary.advanced.ListCompanyAllScenesRequest;
import com.to8to.thrift.diary.advanced.ListCompanyAllScenesResponse;
import com.to8to.thrift.diary.module.TSceneLundan;
import com.to8to.thrift.diary.service.SceneDiaryService;

public class PrepareProcess
{
    private static final Logger logger = LoggerFactory.getLogger(PrepareProcess.class);

    private Map<Integer, Company> companyMap = Maps.newHashMap();

    private Connection connect = DBUtil.getConnectionWithTryCatch();;

    public static void main(String[] args)
    {
        //CrmDataSource.setCrmConfig("jdbc.properties");
        PrepareProcess prepare = new PrepareProcess();
        long s1 = System.currentTimeMillis();
        prepare.zxbOrderInfo();
        long s2 = System.currentTimeMillis();
        System.out.println(prepare.companyMap.size());
        System.out.println(s2 - s1);
    }

    public void prepareCompaynInfo()
    {
        zxbOrderInfo();

        subcomInfo();

        fcomBaseInfo();

        fpInfo();

        gdInfo();
    }

    private void gdInfo()
    {
        if (Utils.isNullOrEmpty(companyMap))
            return;

        Set<Integer> companyIds = companyMap.keySet();

        sceneInfo(companyIds);

        caseInfo(companyIds);
    }

    /**
     * 现场信息，现场和案例构成Company的工地 
     */
    private void sceneInfo(Set<Integer> uids)
    {
        SceneDiaryService.Iface sceneService = CallClient.getInstance().getSceneDiaryService();

        for (Integer uid : uids)
        {
            Company company = getCompany(uid, false);
            if (company == null)
                continue;

            ListCompanyAllScenesRequest req = new ListCompanyAllScenesRequest();
            req.setCom_id(uid);
            try
            {
                ListCompanyAllScenesResponse resp = sceneService.ListCompanyAllScenes(req);
                List<TSceneLundan> scenes = resp.getScenes();
                for (TSceneLundan scene : scenes)
                {
                    GDInfo info = transferScene2GD(scene);
                    if (info.isLegal())
                        setCompanyInfoWithGD(company, info);
                }
            }
            catch (TException e)
            {
                logger.error("调用SceneDiaryService.ListCompanyAllScenes()异常！ {}\n{}", e, LogUtil.logStackTrace(e));
            }
        }
    }

    /**
     * 案例信息 ，现场和案例构成Company的工地 
     */
    private void caseInfo(Set<Integer> uids)
    {
        if (Utils.isNullOrEmpty(uids))
            return;

        String sql =
            String.format("select c.uid,c.saleid,c.style,t.townid from to8to_case as c left join to8to_sale as s on c.saleid = s.sid"
                + " left join to8to_town as t on s.town = t.townname"
                + " where c.uid in (%s) and c.saleid > 0 and s.town <> '' and t.townid > 0  and c.fixsite_id = 0", Utils.collect2Str(uids));

        CachedRowSet rs = DBUtil.executeQuery(connect, sql);

        try
        {
            while (rs.next())
            {
                int uid = rs.getInt("c.uid");
                Company company = getCompany(uid, false);
                if (company == null)
                    continue;
                GDInfo info = new GDInfo();
                info.setUid(rs.getInt("c.uid"));
                info.setSaleId(rs.getInt("c.saleid"));
                info.setTownId(rs.getInt("t.townid"));
                if (info.isLegal())
                {
                    company.getStyles().add(rs.getInt("c.style")); //公司的风格根据案例的风格
                    setCompanyInfoWithGD(company, info);
                }
            }
        }
        catch (SQLException e)
        {
            logger.error("PrepareProcess.caseInfo()异常！ {}\n{}", e, LogUtil.logStackTrace(e));
        }
    }

    /**
     * 轮单信息表，获取公司总的轮单相关信息（价位、公装家装、城市等）。
     */
    private void zxbOrderInfo()
    {
        String sql = "SELECT cityid,areaid,pricelevel,cgate,head_order,end_order FROM to8to_zxb_order";
        Splitter splitter = Splitter.on(",").omitEmptyStrings();
        CachedRowSet rs = DBUtil.executeQuery(connect, sql);

        try
        {
            while (rs.next())
            {
                String comlist = Utils.append(rs.getString("head_order"), rs.getString("end_order"));
                List<String> coms = splitter.splitToList(comlist);
                for (String com : coms)
                {
                    Integer comid = Integer.parseInt(com);
                    Company company = getCompany(comid, true);
                    ZXBOrder order = new ZXBOrder();
                    order.setCityid(rs.getInt("cityid"));
                    order.setCgate(rs.getInt("cgate"));
                    order.setPriceleve(rs.getInt("pricelevel"));
                    order.setAreaid(rs.getInt("areaid"));
                    company.getZxbOrders().add(order);
                }
            }
        }
        catch (SQLException e)
        {
            logger.error("PrepareProcess.zxbOrderInfo()异常！ {}\n{}", e, LogUtil.logStackTrace(e));
        }
    }

    /**
     * 子公司相关信息，获取公司的位置信息、子公司个数
     */
    private void subcomInfo()
    {
        String sql = "SELECT uid,xaxis,yaxis FROM to8to_subcom WHERE ispass=1";
        CachedRowSet rs = DBUtil.executeQuery(connect, sql);
        try
        {
            while (rs.next())
            {
                Company company = getCompany(rs.getInt("uid"), false);
                if (company != null)
                {
                    company.getLocations().add(new GeoPoint(rs.getDouble("xaxis"), rs.getDouble("yaxis")));
                    company.setSubcomCount(company.getSubcomCount() + 1);
                }
            }
        }
        catch (SQLException e)
        {
            logger.error("PrepareProcess.subcomInfo()异常！ {}\n{}", e, LogUtil.logStackTrace(e));
        }
    }

    /**
     * 获取公司的基本信息
     */
    private void fcomBaseInfo()
    {
        String sql = "SELECT f.*,i.offiarea,i.money,i.createdate FROM to8to_fcom as f left join to8to_fcom_info as i on f.id = i.id";

        CachedRowSet rs = DBUtil.executeQuery(connect, sql);
        try
        {
            while (rs.next())
            {
                Company company = getCompany(rs.getInt("f.id"), false);
                if (company != null)
                {
                    company.setBalance(rs.getDouble("f.cancost"));
                    company.setMonthlylimit(rs.getInt("f.monthlylimit"));
                    company.setKoubei(rs.getDouble("f.kbpf"));
                    company.setAptrank(getSgzzNum(rs.getString("f.aptrank")));
                    company.setXinyong(rs.getDouble("f.xinyon"));
                    company.setRegistMoney(rs.getInt("i.money"));
                    company.setOfficeArea(rs.getDouble("i.offiarea"));
                    java.sql.Date date = rs.getDate("i.createdate");
                    company.setCreateTime(date == null ? 0 : (int) (date.getTime() / 1000));
                    int upperlimit = rs.getInt("f.upperlimit");
                    company.setUpperlimit(upperlimit == 0 ? Integer.MAX_VALUE : upperlimit);

                    int dayoff = rs.getInt("f.dayoff");
                    if (dayoff >= 1 && dayoff <= 7)
                        company.setDayoff(dayoff);

                    if (company.getMonthlylimit() > 0)
                    {
                        company.setClassA(true);
                        if (company.getBalance() >= LundanConfig.MIN_BALANCE_CLASSA)
                            company.setHasBalance(true);
                    }
                    else if (company.getBalance() >= LundanConfig.MIN_BALANCE)
                    {
                        company.setHasBalance(true);
                    }

                    int have_tbnums = rs.getInt("f.have_tbnums");
                    int have_tbnums_2 = rs.getInt("f.have_tbnums_2");
                    int have_tbnums_3 = rs.getInt("f.have_tbnums_3");
                    int have_tbnums_4 = rs.getInt("f.have_tbnums_4");
                    int have_tbnums_5 = rs.getInt("f.have_tbnums_5");
                    int have_tbnums_6 = rs.getInt("f.have_tbnums_6");
                    int have_tbnums_7 = rs.getInt("f.have_tbnums_7");

                    if (have_tbnums > 0)
                        company.getTbnumsMap().put("1", have_tbnums);
                    if (have_tbnums_2 > 0)
                        company.getTbnumsMap().put("2", have_tbnums_2);
                    if (have_tbnums_3 > 0)
                        company.getTbnumsMap().put("3", have_tbnums_3);
                    if (have_tbnums_4 > 0)
                        company.getTbnumsMap().put("4", have_tbnums_4);
                    if (have_tbnums_5 > 0)
                        company.getTbnumsMap().put("5", have_tbnums_5);
                    if (have_tbnums_6 > 0)
                        company.getTbnumsMap().put("6", have_tbnums_6);
                    if (have_tbnums_7 > 0)
                        company.getTbnumsMap().put("7", have_tbnums_7);
                }
            }
        }
        catch (SQLException e)
        {
            logger.error("PrepareProcess.fcomBaseInfo()异常！ {}\n{}", e, LogUtil.logStackTrace(e));
        }
    }

    /**
     * 获取分配的相关数据
     */
    private void fpInfo()
    {
        int startPuttime = Utils.getHoursAgo(31 * 24); //31天之内的分配
        int monthStartTime = Utils.getMonthStart();
        String sql =
            String.format("select f.yid,f.uid,f.cglf,a.pricelevel,a.puttime from to8to_yuyue_apply_fp as f left join to8to_yuyue_apply as a on f.yid = a.yid where f.puttime > %s", startPuttime);

        CachedRowSet rs = DBUtil.executeQuery(connect, sql);

        try
        {
            while (rs.next())
            {
                int comid = rs.getInt("f.uid");
                int pricelevel = rs.getInt("a.pricelevel");
                int puttime = rs.getInt("f.puttime");
                Company company = getCompany(comid, false);
                company.setFpCount(company.getFpCount() + 1);
                if (rs.getInt("f.cglf") == 1)
                    company.setLfSuccCount(company.getLfSuccCount() + 1);
                Integer count = company.getPriceFpMap().get(String.valueOf(pricelevel));
                company.getPriceFpMap().put(String.valueOf(pricelevel), count == null ? 1 : count + 1);
                if (puttime >= monthStartTime && puttime >= 1415462400)
                    company.setMonthFpCount(company.getMonthFpCount() + 1);
            }
        }
        catch (SQLException e)
        {
            logger.error("PrepareProcess.fpInfo()异常！ {}\n{}", e, LogUtil.logStackTrace(e));
        }
    }

    /**
     * 从CompanyMap中获取公司信息
     * @param comid 公司id
     * @param createIfNotExist 没有时是否创建
     */
    private Company getCompany(int comid, boolean createIfNotExist)
    {
        Company company = companyMap.get(comid);
        if (company == null && createIfNotExist)
        {
            company = new Company();
            company.set_id(comid);
            companyMap.put(comid, company);
        }
        return company;
    }

    /**
     * 获取施工资质对应的数字
     */
    private static int getSgzzNum(String text)
    {
        String tmp = text.replace("级", "");
        tmp = StringUtil.Cn2Num(tmp);
        if (StringUtil.isNumeric(tmp))
            return Integer.parseInt(tmp);
        return 0;
    }

    /**
     * 将现场信息转换为工地信息 
     */
    private GDInfo transferScene2GD(TSceneLundan scene)
    {
        GDInfo info = new GDInfo();
        info.setUid(scene.getCom_id());
        info.setSaleId(scene.getComm_id());
        info.setTownId(scene.getTown_id());
        return info;
    }

    /**
     * 设置Company和工地相关的信息
     */
    private void setCompanyInfoWithGD(Company company, GDInfo info)
    {
        company.getGdList().add(info);
        Integer count = company.getTownGDMap().get(info.getTownId());
        company.getTownGDMap().put(info.getTownId(), count == null ? 1 : count + 1);
    }
}
